'use strict';

import Base from './base.js';

const jwt = require('jsonwebtoken');
export default class extends Base {
  // 手机号登录
  async loginAction() {
    const that = this;
    const tel = that.post('tel');
    const pass = that.post('pass');
    const code = that.post('code');
    const departmentid = that.post('departmentid');
    if (!/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/i.test(tel)) {
      return that.json({statusCode: '100', msg: '手机号不正确'});
    }
    if (think.isEmpty(pass)) {
      return that.json({statusCode: '100', msg: '密码不能为空'});
    }
    // 获取session_key 和用户openid
    const userinfo = await that.model('or_guest').where({username: tel}).field('id,departmentid,name,password,sex,headurl,openid,balance,giftbalance').find();
    if (think.isEmpty(userinfo)) {
      return that.json({statusCode: '100', msg: '用户不存在'});
    }
    if (think.md5(pass) !== userinfo.password) {
      return that.json({statusCode: '100', msg: '密码错误'});
    }
    // 判断用户是否属于该机构
    const shopinfo = await that.model('or_department').where({id: userinfo.departmentid}).find();
    if (shopinfo.pid != departmentid) {
      return that.json({statusCode: '100', msg: '用户不属于该机构'});
    }
    // 获取appid和secret
    const data = await that.model('or_weixin_config').where({departmentid: departmentid}).find();
    // 获取用户openid
    const os = await that.fetch('https://api.weixin.qq.com/sns/jscode2session?appid=' + data.appid + '&secret=' + data.secret + '&js_code=' + code + '&grant_type=authorization_code').then(res => res.json());
    // 判断用户是否绑定openid
    if (think.isEmpty(userinfo.openid)) {
      // 用户绑定openid
      const affectedRows = await that.model('or_guest').where({username: tel}).update({openid: os.openid});
    }
    delete userinfo.password;
    delete userinfo.openid;
    // 生成token
    const token = jwt.sign(os, think.config('mytmini.jwtSecret'), {expiresIn: '7d'});
    return that.json({statusCode: '200', msg: '登录成功', data: {token: token, userinfo: userinfo}});
  }

  // 微信快速登录
  async wxloginAction() {
    const that = this;
    const code = that.post('code');
    const departmentid = that.post('departmentid');
    // 获取appid和secret
    const data = await that.model('or_weixin_config').where({departmentid: departmentid}).find();
    // 根据code获取openid
    const os = await that.fetch('https://api.weixin.qq.com/sns/jscode2session?appid=' + data.appid + '&secret=' + data.secret + '&js_code=' + code + '&grant_type=authorization_code').then(res => res.json());
    const openid = os.openid;
    // 判断此openid是否绑定过
    const userinfo = await that.model('or_guest')
      .alias('g')
      .field('g.id,g.departmentid,g.name,g.sex,g.headurl,g.balance,g.giftbalance')
      .join('left join `think_or_department` d on g.departmentid = d.id')
      .where({
        'g.openid': openid,
        'd.pid': departmentid
      })
      .find();
    if (think.isEmpty(userinfo)) {
      return that.json({statusCode: '100', msg: '请验证手机号和密码'});
    }
    // 生成token
    const token = jwt.sign(os, think.config('mytmini.jwtSecret'), {expiresIn: '7d'});
    return that.json({statusCode: '200', msg: '登录成功', data: {token: token, userinfo: userinfo}});
  }

  // 更改密码
  async changepassAction() {
    const that = this;
    const oldpass = think.md5(that.post('oldpass'));
    const newpass = think.md5(that.post('newpass'));
    const confirmpass = think.md5(that.post('confirmpass'));
    const openid = that.getuseropenid();
    if (newpass !== confirmpass) {
      return that.json({statusCode: '100', msg: '两次输入密码不一致'});
    }
    const res = await that.model('or_guest').where({openid: openid}).field('password').find();
    console.log(res.password);
    if (res.password !== oldpass) {
      return that.json({statusCode: '100', msg: '原密码不正确'});
    }

    const affectedRows = await that.model('or_guest').where({openid: openid}).update({password: newpass});
    return affectedRows ? that.json({statusCode: '200', msg: '密码更改成功'}) : that.json({statusCode: '100', msg: '密码更改失败'});
  }

  // 客户暂存
  async getgueststorageAction() {
    const that = this;
    const guestid = that.post('guestid');
    const where = {
      'tr.guestid': guestid,
      'tr.nownum': ['>', 0],
      'tr.isdisabled': 0
    };
    const list = await that.model('or_shop_guest_temp_reserve')
      .alias('tr')
      .field('tr.*, g.name')
      .join('left join `think_or_goods` g on tr.goodsid = g.id')
      .where(where)
      .select();
    return that.json(list);
  }

  // 客户项目
  async getguestprojectAction() {
    const that = this;
    const guestid = that.post('guestid');
    const nowtime = Date.parse(new Date()) / 1000;
    let where = 'gs.guestid = ' + guestid;
    where += ' and gs.isdisabled = 0';
    where += ' and ((' + nowtime + ' < gs.endtime and gs.cardtype = 1) or (gs.nownum > 0 and gs.cardtype = 2))';
    const list = await that.model('or_shop_guestcardsubject')
      .alias('gs')
      .field('gs.*, s.name as subjectname,c.name as cardname')
      .join('left join `think_or_subject` s on gs.subjectid = s.id')
      .join('left join `think_or_shop_card` c on gs.cardid = c.id')
      .where(where)
      .select();
    return that.json(list);
  }

  // 客户消费记录
  async getbuyrecordsAction() {
    const that = this;
    const shopid = that.post('shopid');
    const guestid = that.post('guestid');
    const where = {
      'so.guestid': guestid,
      'so.departmentid': shopid
    };
    const list = await that.model('or_shop_order')
      .alias('so')
      .field('so.*, IFNULL(oi.price,0) as price')
      .join('left join `think_or_shop_orderinfo` oi on oi.orderid = so.id and oi.type=5')
      .where(where)
      .select();
    return that.json(list);
  }

  // 客户退款记录
  async getrefundrecordsAction() {
    const that = this;
    const shopid = that.post('shopid');
    const guestid = that.post('guestid');
    const where = {
      'sb.guestid': guestid,
      'sb.departmentid': shopid
    };
    const list = await that.model('or_shop_backcardorder')
      .alias('sb')
      .where(where)
      .select();
    return that.json(list);
  }

  // 客户订单详细
  async getorderdetailAction() {
    const that = this;
    const orderid = that.post('orderid');
    const where = {
      'orderid': orderid
    };
    const list = await that.model('or_shop_orderinfo')
      .where(where)
      .select();
    return that.json(list);
  }

  // 客户预约单
  async getreservationAction() {
    let that = this
    const guestid = that.post('guestid');
    // 获取信息
    const list = await that.model('or_appointment')
      .alias('am')
      .field('am.*, au.name as uname, sb.name as sname')
      .join('think_or_app_user au on am.userid = au.id')
      .join('think_or_subject sb on am.subjectid = sb.id')
      .where({'am.guestid': guestid})
      .order('am.id desc')
      .select();
    return that.json(list);
  }
}
